# -*- coding: utf-8 -*-
# @Time     : 2021/11/27 17:00
# @Author   : wljess
# @File     : 上下文管理器实现mysql连接.py
# @Describe : 
# @Software : PyCharm

import pymysql


class DataBase:

    def __init__(self, host, username, pwd, db_name):
        self.coon = pymysql.connect(host=host, user=username, passwd=pwd, database=db_name)
        self.cursor = self.coon.cursor()

    def __enter__(self):

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.coon.close()
        self.cursor.close()

    def query(self, sql):
        self.cursor.execute(sql)
        result = self.cursor.fetchone()
        return result


with DataBase("localhost", "root", "", "mydb") as db:
    print(db.query("select name,age,salary from user_table where id=4947;"))
